/*
 * Copyright (c) 2019-2020, https://api.iot.10086.cn/(https://gitee.com/cmcc-iot-api/iot-card-open-application/).
 */
package cn.iot.card.open.sim.service;

import cn.iot.card.open.constants.Constants;
import cn.iot.card.open.constants.ErrorCode;
import cn.iot.card.open.constants.UrlConstants;
import cn.iot.card.open.ec.dto.ResponseDto;
import cn.iot.card.open.modular.model.ResultDTO;
import cn.iot.card.open.modular.token.TokenService;
import cn.iot.card.open.pojo.page.LayuiPageFactory;
import cn.iot.card.open.pojo.page.LayuiPageInfo;
import cn.iot.card.open.sim.dto.general.SimRechargeDTO;
import cn.iot.card.open.sim.dto.general.SimRechargeOrderDTO;
import cn.iot.card.open.sim.dto.general.SimRechargeResponseDTO;
import cn.iot.card.open.util.ApiRequestUtil;
import cn.iot.card.open.util.CommonUtil;
import cn.iot.card.open.util.JsonUtil;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 物联卡综合信息-充值服务实现类
 *
 * @author 何光鑫
 * @date 20200325 15:26:49
 * @modify 20200325 何光鑫 v1.1.2.1 创建
 * @since v1.1.2.1
 */
@Service
@Slf4j
public class GeneralRechargeService {

    /**
     * apiRequestUtil
     */
    @Autowired
    private ApiRequestUtil apiRequestUtil;

    /**
     * tokenService
     */
    @Autowired
    private TokenService tokenService;

    /**
     * 调用api接口实现充值结果查询
     *
     * @param transId
     * @param accountId 集团id
     * @param parameterMap 调用api接口的请求参数
     * @return 返回 layui page info
     * @throws IOException
     * @author 何光鑫
     * @date 20200325 15:26:49
     * @modify 20200325 何光鑫 v1.1.2.1 创建
     * @since v1.1.2.1
     */
    public LayuiPageInfo queryRechargeResult(String transId, String accountId , Map<String, String> parameterMap) throws IOException {
        Page page = LayuiPageFactory.defaultPage();
        //封装请求参数
        String startNum = String.valueOf(page.getCurrent());
        String pageSize = String.valueOf(page.getSize());
        parameterMap.put(Constants.REQUEST_PARAM_STARTNUM, startNum);
        parameterMap.put(Constants.REQUEST_PARAM_PAGESIZE, pageSize);
        String url = UrlConstants.SIM_ACCOUNT_RECHARGE_RESULT;
        // 调用api接口：先获取token，然后带着token调用api接口
        ResultDTO tokenResultDTO = doRequest(true, accountId, transId,parameterMap,url);
        // 如果此处响应失败即为获取token失败，返回失败原因
        if (!tokenResultDTO.getCode().equals(ErrorCode.SUCCESS.getCode())) {
            ErrorCode errorCode = ErrorCode.getByCode(tokenResultDTO.getCode());
            log.warn("[{}] query rechargeResult token error first,error message is {}.", transId, errorCode.getMsg());
            return LayuiPageFactory.cteateErrorMsg(errorCode);
        }
        // 获取token成功后解析api接口的响应结果
        String responseStr = tokenResultDTO.getMsg();
        String code = CommonUtil.getApiRspCode(responseStr);
        // 获取api接口的响应结果状态码，如果状态码为12021（token不存在或已过期），则重新获取token后再次调用api接口
        if (ErrorCode.ERR12021.getCode().equals(code)) {
            log.warn("[{}] token[accountId:{}] of query rechargeResult is invalid and start to get a new token.", transId, accountId);
            tokenResultDTO = doRequest(false, accountId, transId, parameterMap, url);
            // 如果此处响应失败即为获取token失败，返回失败原因
            if (!tokenResultDTO.getCode().equals(ErrorCode.SUCCESS.getCode())) {
                ErrorCode errorCode = ErrorCode.getByCode(tokenResultDTO.getCode());
                log.warn("[{}] query rechargeResult token error second,error message is {}.",transId, errorCode.getMsg());
                return LayuiPageFactory.cteateErrorMsg(errorCode);
            }
            // 获取token成功后，重置responseStr（api接口的响应结果）
            responseStr = tokenResultDTO.getMsg();
        }
        log.info("[{}] query result string is {}.",transId, responseStr);
        // 组装页面信息
        ResponseDto<SimRechargeDTO> result = JsonUtil.parseJson(responseStr, new TypeReference<ResponseDto<SimRechargeDTO>>() {});
        code = result.getStatus();
        if (!ErrorCode.SUCCESS.getCode().equals(code)) {
            // 如果api接口返回失败，则返回失败原因
            log.warn("[{}] query rechargeResult error,error message is {}.",transId, result.getMessage());
            return LayuiPageFactory.cteateErrorMsg(ErrorCode.getByCode(code));
        }
        List<SimRechargeDTO> simRechargeDTOS = result.getResult();
        if (ToolUtil.isEmpty(simRechargeDTOS)) {
            log.warn("[{}] query rechargeResult end,result is null.",transId);
            return LayuiPageFactory.createEmptyPageInfo();
        }
        List<SimRechargeOrderDTO> orderList = simRechargeDTOS.get(0).getOrderList();
        page.setTotal(Long.valueOf(simRechargeDTOS.get(0).getTotalCount()));
        page.setRecords(orderList);
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 物联卡账户充值交费
     *
     * @param transId
     * @param accountId 集团账户id
     * @param entityType 充值标识类型：1：msisdn，2：账户Id
     * @param entityId 充值标识类型对应号码
     * @param chargeMoney 充值金额
     * @param paymentType 支付方式
     * @param returnUrl 支付成功后跳转页面的URL
     * @param defaultBank 默认网银
     * @return 返回 response data
     * @throws IOException
     * @author 何光鑫
     * @date 20200325 15:26:50
     * @modify 20200325 何光鑫 v1.1.2.1 创建
     * @since v1.1.2.1
     */
    public ResponseData rechargeSimAccount(String transId, String accountId, String entityType,String entityId,String chargeMoney,String paymentType
            ,String returnUrl,String defaultBank) throws IOException {
        ResponseData responseData = new ResponseData();
        // 封装调用api接口的参数
        Map<String, String> parameterMap = new HashMap<>();
        String url = UrlConstants.RECHARGE_SIM_ACCOUNT;
        parameterMap.put(Constants.RESPONSE_ENTITY_TYPE,entityType);
        parameterMap.put(Constants.RESPONSE_ENTITY_ID,entityId);
        parameterMap.put(Constants.RESPONSE_CHARGE_MONEY,chargeMoney);
        parameterMap.put(Constants.RESPONSE_PAYMENT_TYPE,paymentType);
        parameterMap.put(Constants.RESPONSE_RETURN_URL,returnUrl);
        parameterMap.put(Constants.RESPONSE_DEFAULT_BANK,defaultBank);
        // 调用api接口：先获取token，然后带着token调用api接口
        ResultDTO tokenResultDTO = doRequest(true, accountId, transId, parameterMap,url);
        // 如果此处响应失败即为获取token失败，返回失败原因
        if (!tokenResultDTO.getCode().equals(ErrorCode.SUCCESS.getCode())) {
            ErrorCode errorCode = ErrorCode.getByCode(tokenResultDTO.getCode());
            log.warn("[{}] rechargeSimAccount token error first,error message is {}.",transId, errorCode.getMsg());
            responseData.setCode(Integer.valueOf(errorCode.getCode()));
            responseData.setMessage(errorCode.getMsg());
        }
        // 获取token成功后解析api接口的响应结果
        String responseStr = tokenResultDTO.getMsg();
        String code = CommonUtil.getApiRspCode(responseStr);
        // 获取api接口的响应结果状态码，如果状态码为12021（token不存在或已过期），则重新获取token后再次调用api接口
        if (ErrorCode.ERR12021.getCode().equals(code)) {
            log.warn("[{}] token[accountId:{}] of rechargeSimAccount is invalid and start to get a new token.", transId, accountId);
            tokenResultDTO = doRequest(false, accountId, transId,  parameterMap,url);
            // 如果此处响应失败即为获取token失败，返回失败原因
            if (!tokenResultDTO.getCode().equals(ErrorCode.SUCCESS.getCode())) {
                ErrorCode errorCode = ErrorCode.getByCode(tokenResultDTO.getCode());
                log.warn("[{}] rechargeSimAccount token error second,error message is {}.",transId, errorCode.getMsg());
                responseData.setCode(Integer.valueOf(errorCode.getCode()));
                responseData.setMessage(errorCode.getMsg());
            }
            // 获取token成功后，重置responseStr（api接口的响应结果）
            responseStr = tokenResultDTO.getMsg();
        }
        log.info("[{}] rechargeSimAccount result string is {}.", transId, responseStr);
        // 解析api响应结果
        ResponseDto<Map<String, String>> responseDto = JsonUtil.parseJson(responseStr,
                new TypeReference<ResponseDto<Map<String, String>>>(){});
        code = responseDto.getStatus();
        if (ErrorCode.SUCCESS.getCode().equals(code)) {
            String responseUrl = responseDto.getResult().get(0).get(Constants.RESPONSE_URL);
            String responseOrderNo = responseDto.getResult().get(0).get(Constants.RESPONSE_ORDER_NO);
            SimRechargeResponseDTO simRechargeResponseDTO = new SimRechargeResponseDTO();
            simRechargeResponseDTO.setUrl(responseUrl);
            simRechargeResponseDTO.setOrderNo(responseOrderNo);
            return ResponseData.success(simRechargeResponseDTO);
        } else {
            // 如果api接口返回失败，则返回失败原因
            log.warn("[{}] rechargeSimAccount error, error message is {}.", transId, responseDto.getMessage());
            responseData = new ResponseData();
            responseData.setCode(Integer.valueOf(code));
            responseData.setMessage(responseDto.getMessage());
            return responseData;
        }
    }

    /**
     * request 请求
     *
     * @param tokenValid true表示使用已经初始化了的token值，false表示使用重新生成的token值
     * @param accountId 集团id
     * @param transId
     * @param parameterMap 调用api接口的参数
     * @param url 调用API接口的请求路径
     * @return 返回 API接口响应结果（或者获取token失败的原因）
     * @throws IOException
     * @author 何光鑫
     * @date 20200316 21:45:40
     * @modify 20200316 何光鑫 v1.1.2 创建
     * @since v1.1.2
     */
    private ResultDTO doRequest(boolean tokenValid, String accountId, String transId, Map<String, String> parameterMap, String url) throws IOException {
        // 根据 accountId 查询 token
        ResultDTO tokenResultDTO = tokenService.getToken(tokenValid, accountId);
        if (!tokenResultDTO.getCode().equals(ErrorCode.SUCCESS.getCode())) {
            return tokenResultDTO;
        }
        parameterMap.put(Constants.REQUEST_PARAM_TOKEN, tokenResultDTO.getMsg());
        parameterMap.put(Constants.REQUEST_PARAM_TRANSID, transId);
        String methodUrl = apiRequestUtil.buildRequestUrl(parameterMap, url);
        log.info("[{}] query generalRecharge request url is {}.", transId, methodUrl);
        tokenResultDTO.setMsg(apiRequestUtil.doGet(methodUrl));
        return tokenResultDTO;
    }
}
